package io.github.fb513.api.facade;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import io.github.fb513.api.entity.UserOnline;
import io.github.fb513.api.enums.ActiveUserStatusEnum;
import io.github.fb513.api.queue.MessageSender;
import io.github.fb513.api.service.IUserOnlineService;
import io.github.fb513.common.enums.CommandEnum;
import io.github.fb513.common.model.BaseData;
import io.github.fb513.common.model.LoginData;
import io.github.fb513.common.model.MessageInfo;
import io.github.fb513.common.util.ImUtils;
import io.github.fb513.common.util.JsonParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author fengbo
 * @since 2023/12/26 9:28
 */
@Component
public class LoginFacade {

    @Autowired private IUserOnlineService userOnlineService;
    @Autowired private MessageSender messageSender;
    @Autowired private JsonParser jsonParser;

    public void imLogin(BaseData<?> baseData) {
        LoginData loginData = (LoginData) baseData.getContent();
        UserOnline activeUser = userOnlineService.getOne(new LambdaQueryWrapper<UserOnline>()
                .select(UserOnline::getId)
                .eq(UserOnline::getUserId, baseData.getUserId())
                .eq(UserOnline::getClientType, baseData.getClientType())
        );
        if (activeUser == null) {
            // 用户未登录 TODO
        }
        activeUser.setActiveStatus(ActiveUserStatusEnum.ONLINE.getCode());
        activeUser.setBrokerHost(loginData.getBrokerHost());
        activeUser.setBrokerPort(loginData.getBrokerPort());
        userOnlineService.updateById(activeUser);

        MessageInfo<BaseData<?>> resp = MessageInfo.getJsonMessage(CommandEnum.LOGIN_SUCCESS.getCommand(),
                new BaseData<>(baseData.getUserId(), baseData.getClientType()));
        messageSender.send(ImUtils.getBrokerKey(loginData.getBrokerHost(), loginData.getBrokerPort()),
                jsonParser.formatObjToJson(resp));
    }

    public void imLogout(BaseData<?> baseData) {
        UserOnline activeUser = userOnlineService.getOne(new LambdaQueryWrapper<UserOnline>()
                .select(UserOnline::getId)
                .eq(UserOnline::getUserId, baseData.getUserId())
                        .eq(UserOnline::getClientType, baseData.getClientType())
                .eq(UserOnline::getActiveStatus, ActiveUserStatusEnum.ONLINE.getCode())
                .last("limit 1")
        );
        if (activeUser == null) {
            return;
        }
        userOnlineService.update(new LambdaUpdateWrapper<UserOnline>()
                .set(UserOnline::getActiveStatus, ActiveUserStatusEnum.OFFLINE.getCode())
                .eq(UserOnline::getId, activeUser.getId()));
    }
}
